理解 Integer 和 int 的区别

基础类型和封装类型的区别

1、传递方式不同
封装类是引用类型,基本类型(原始数据类型)在传递参数时都是按值传递,而封装类型是按引用传递的(其实“引用也是按值传递的”,传递的是对象的地址)。由于引用类型都是不可变量,因此没有提供改变它的值的方法,增加了对“按引用传递”的理解难度。
int 是基本类型,直接存放数值;Integer 是类,产生对象时用一个引用指向这个对象。

2、封装类可以有方法和属性
封装类可以有方法和属性,利用这些方法和属性来处理数据,如 Integer.parseInt(Strings)。基本数据类型都是 final 修饰的,不能继承扩展新的类、新的方法。

3、默认值不同
基本类型跟封装类型的默认值是不一样的。如 int i,i 的预设为 0;Integer j,j 的预设为 null,因为封装类产生的是对象,对象默认值为 null。

4、存储位置不同
基本类型在内存中是存储在栈中,引用类型的引用(值的地址)存储在栈中,而实际的对象(值)是存在堆中。

Integer 和 int 的区别

1、Integer 是 int 的包装类,而 int 是一种基本数据类型。
2、Integer 变量必须实例化后才能使用,而 int 变量不需要。
3、Integer 实际是对象的引用,当 new 一个 Integer 时,实际上是生成一个指针指向此对象;而 int 则是直接存储数据值。
4、Integer 的默认值是 null,int 的默认值是 0。

Integer 和 int 的比较

比较两个 new 出来的 Integer

1
2
3
4
5
6
7
8
9
10
11
/**
* 比较两个 new 出来的 Integer
*/
public class Test {
public static void main(String[] args) {
Integer i = new Integer(200);
Integer j = new Integer(200);
System.out.print(i == j);
//输出:false
}
}

Integer 变量实际上是对一个 Integer 对象的引用。当 new 一个 Integer 时,实际上是生成一个指针指向此对象,两次 new Integer 生成的是两个对象,其内存地址不同,所以两个 new 出来的 Integer 变量不相等。

比较非 new 生成的 Integer 变量与 new 生成的 Integer 变量

1
2
3
4
5
6
7
8
9
10
11
/**
* 比较非 new 生成的 Integer 变量与 new 生成的 Integer 变量
*/
public class Test {
public static void main(String[] args) {
Integer i = new Integer(200);
Integer j = 200;
System.out.print(i == j);
//输出:false
}
}

因为非 new 生成的 Integer 变量指向的是 java 常量池中的对象,而 new Integer() 生成的变量指向堆中新建的对象,两者在内存中的地址不同,所以输出为 false。

比较两个非 new 生成的 Integer 变量

1
2
3
4
5
6
7
8
9
10
11
12
13
/**
* 比较两个非 new 生成的 Integer 变量
*/
public class Test {
public static void main(String[] args) {
Integer i1 = 127;
Integer j1 = 127;
System.out.println(i1 == j1); //输出:true
Integer i2 = 128;
Integer j2 = 128;
System.out.println(i2 == j2); //输出:false
}
}

java 在编译 Integer i1 = 127 时,会翻译成 Integer i1 = Integer.valueOf(127),查看Interger源码:

1
2
3
4
5
6
7
8
/* This method will always cache values in the range -128 to 127,
* inclusive, and may cache other values outside of this range.
*/
public static Integer valueOf(int i) {
if (i >= IntegerCache.low && i <= IntegerCache.high)
return IntegerCache.cache[i + (-IntegerCache.low)];
return new Integer(i);
}

可以看出,java 会将 [-128,127] 之间的数进行缓存。Integer i1 = 127 时,会将 127 缓存,Integer j2 = 127 时,就直接从缓存中取,不会 new 了,所以结果为 true。

Integer i2 = 128 时,不会将 128 缓存,Integer j2 = 128 时,会 return new Integer(128),所以结果为 false。

比较 Integer 变量与 int 变量

1
2
3
4
5
6
7
8
9
10
11
12
/**
* 比较 Integer 变量与 int 变量
*/
public class Test {
public static void main(String[] args) {
Integer i1 = 200;
Integer i2 = new Integer(200);
int j = 200;
System.out.println(i1 == j); //输出:true
System.out.println(i2 == j); //输出:true
}
}

包装类 Integer 变量在与基本数据类型 int 变量比较时,Integer 会自动拆包装为 int,然后进行比较,实际上就是两个 int 变量进行比较,值相等,所以为 true。

Powered by Hexo and Hexo-theme-hiker

Copyright © 2013 - 2019 kevinyangI All Rights Reserved.

UV : | PV :